<template>
  <div>
    <el-image
        :src="realSrc"
        fit="cover"
        :style="`width:${realWidth};height:${realHeight};`"
        :preview-src-list="realSrcList"
        append-to-body="true"
        @click.native.stop
        :preview-teleported="true"
    >
      <template #error>
        <div class="image-slot">
          <el-icon><picture-filled /></el-icon>
        </div>
      </template>
      <template #placeholder>
        <div class="image-slot">
          <el-icon><picture-filled /></el-icon>
        </div>
      </template>
      <div class="preview-mask" v-show="previewVisible" @click="closePreview"></div>
    </el-image>
  </div>
</template>

<script setup>
import { defineProps, computed, ref, watch } from 'vue';

const props = defineProps({
  src: {
    type: [String],
    default: ""
  },
  srcList: {
    type: Array,
    default: () => []
  },
  width: {
    type: [Number, String],
    default: ""
  },
  height: {
    type: [Number, String],
    default: ""
  }
});

const realSrc = computed(() => {
  if (props.src && typeof props.src === 'string') {
    return props.src;
  }

  if (!props.srcList || props.srcList.length === 0) {
    return '';
  }

  return props.srcList[0];
});

const realSrcList = computed(() => {
  if (!props.srcList || props.srcList.length === 0) {
    return props.src ? [props.src] : [];
  }
  return props.srcList;
});

const realWidth = computed(() =>
    typeof props.width == "string" ? props.width : `${props.width}px`
);

const realHeight = computed(() =>
    typeof props.height == "string" ? props.height : `${props.height}px`
);

const previewVisible = ref(false);

const closePreview = () => {
  previewVisible.value = false;
};

const overlayVisible = computed(() => {
  return previewVisible.value;
});

watch(overlayVisible, (value) => {
  if (value) {
    document.body.style.overflow = "hidden";
  } else {
    document.body.style.overflow = "";
  }
});
</script>

<style lang="scss" scoped>
.el-image {
  position: relative;
  border-radius: 5px;
  background-color: #ebeef5;
  box-shadow: 0 0 5px 1px #ccc;

  :deep(.el-image__inner) {
    transition: all 0.3s;
    cursor: pointer;

    &:hover {
      transform: scale(1.2);
    }
  }

  :deep(.image-slot) {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    color: #909399;
    font-size: 30px;
  }

  .preview-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 9999;

    // 添加透明的 div 阻止点击事件传递
    &::before {
      content: "";
      display: block;
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      pointer-events: none; // 阻止点击事件传递
    }

    background-color: rgba(0, 0, 0, 0.8);
    cursor: pointer;
    user-select: none; // 阻止文本选择
  }
}
</style>
